const fs = require('fs');
const assert = require('assert');
const fetch = require('node-fetch');

const conf = require('./conf');
const java = require('./java');
const FormData = require('form-data');

// const daka_day = '2022-03-07';
const daka_day = today();

(async () => {
    console.log('getParent');
    const datas = await getParent();
    for (let i = 0; i < datas.length; i++) {
        console.log(datas[i].title, datas[i].text_content);
        if (datas[i]['is_today']) {
            await check2dakaNew2(datas[i]);
        } else {
            console.log('>>>跳过。。。');
        }
    }
})().catch(err => console.log(err));

async function check2dakaNew2(data) {
    console.log('check2dakaNew2', '_id=' + data._id, 'cid=' + data.cls);
    const res = await POST(`https://a.welife001.com/applet/notify/check2dakaNew2`, {
        "_id": data._id,
        "cid": data.cls,
        "daka_day": "",
        "click_load": false,
        "teacher_cate": "",
        "member_id": conf.memberId,
        "cls_ts": new Date(daka_day + ' 06:36:00').getTime(),
    });
    const invest = await buildInvest(res.data.notify.invest);
    await feedbackWithOss(data._id, invest);
}

async function feedbackWithOss(_id, invest) {
    console.log('feedbackWithOss', _id);
    await POST(`https://a.welife001.com/applet/notify/feedbackWithOss`, {
        feedback_text: "",
        id: _id,
        daka_day: daka_day,
        files: [],
        file_type: "",
        form_id: "",
        submit_type: "submit",
        networkType: "wifi",
        member_id: conf.memberId,
        examdetail: "",
        invest: invest,
        op: "add",
        sub_info: []
    });
}

async function buildInvest(invest) {
    console.log('buildInvest', invest._id);
    for (let i = 0; i < invest.subject.length; i++) {
        console.log(invest.subject[i].title);
        switch (invest.subject[i].title) {
            case '幼儿姓名':
                invest.subject[i].valid = true;
                invest.subject[i].input = { 'content': conf.child };
                break;
            case '幼儿健康码':
                invest.subject[i].item_details[0].checked = true;
                invest.subject[i].item_details[1].checked = false;
                invest.subject[i].item_details[2].checked = false;
                invest.subject[i].valid = true;
                break;
            case '幼儿当日健康码截图':
                const child = await genQrcode('child');
                invest.subject[i].input = { "file": [{ "file": child.file, "id": child.id }] };
                invest.subject[i].valid = true;
                break;
            case '目前所在地；幼儿昨晚体温；今晨体温（如：上海；37；37）':
                invest.subject[i].valid = true;
                invest.subject[i].input = { 'content': '湖南衡东 ' + wd() + ' ' + wd() };
                break;
            case '幼儿有无下列症状':
                invest.subject[i].item_details[0].checked = false;
                invest.subject[i].item_details[1].checked = false;
                invest.subject[i].item_details[2].checked = false;
                invest.subject[i].item_details[3].checked = false;
                invest.subject[i].item_details[4].checked = false;
                invest.subject[i].item_details[5].checked = false;
                invest.subject[i].item_details[6].checked = false;
                invest.subject[i].item_details[7].checked = false;
                invest.subject[i].item_details[8].checked = false;
                invest.subject[i].item_details[9].checked = false;
                invest.subject[i].item_details[10].checked = true;
                invest.subject[i].valid = true;
                break;
            case '幼儿当前防疫状态':
                invest.subject[i].item_details[0].checked = true;
                invest.subject[i].item_details[1].checked = false;
                invest.subject[i].item_details[2].checked = false;
                invest.subject[i].item_details[3].checked = false;
                invest.subject[i].item_details[4].checked = false;
                invest.subject[i].valid = true;
                break;
            case '所有同住人':
                invest.subject[i].item_details[0].checked = false;
                invest.subject[i].item_details[1].checked = true;
                invest.subject[i].item_details[2].checked = false;
                invest.subject[i].item_details[3].checked = false;
                invest.subject[i].item_details[4].checked = false;
                invest.subject[i].item_details[5].checked = false;
                invest.subject[i].item_details[6].checked = false;
                invest.subject[i].valid = true;
                break;
            case '所有同住人健康码情况':
                invest.subject[i].item_details[0].checked = true;
                invest.subject[i].item_details[1].checked = false;
                invest.subject[i].valid = true;
                break;
            case '所有同住人当日健康码截图':
                const mama = await genQrcode('mama');
                invest.subject[i].input = { "file": [{ "file": mama.file, "id": mama.id }] };
                invest.subject[i].valid = true;
                break;
            case '所有同住人当日行程码截图':
                const mama2 = await genXCM('mama2');
                invest.subject[i].input = { "file": [{ "file": mama2.file, "id": mama2.id }] };
                invest.subject[i].valid = true;
                break;
            case '所有同住人体温（如父亲37；母亲37；等其余同住人体温）':
                invest.subject[i].valid = true;
                invest.subject[i].input = { "content": wd() };
                break;
            case '同住人当前防疫状态':
                invest.subject[i].item_details[0].checked = true;
                invest.subject[i].item_details[1].checked = false;
                invest.subject[i].item_details[2].checked = false;
                invest.subject[i].item_details[3].checked = false;
                invest.subject[i].item_details[4].checked = false;
                invest.subject[i].valid = true;
                break;
            case '当前居住地':
                invest.subject[i].valid = true;
                invest.subject[i].input = { "content": '上海市浦东新区益江路516弄5-201' };
                break;
            case '居住地有无特殊情况':
                invest.subject[i].item_details[0].checked = true;
                invest.subject[i].item_details[1].checked = false;
                invest.subject[i].item_details[2].checked = false;
                invest.subject[i].valid = true;
                break;
            case '本人承诺以上提供的资料真实准确，如有不实，本人愿意承担由此引起的一切后果及法律责任。承诺人签字：':
                invest.subject[i].valid = true;
                invest.subject[i].input = { "content": conf.mama };
                break;
            default:
                break;
        }
    }
    return invest;
}

// 健康码
async function genQrcode(who) {
    console.log('健康码', daka_day)
    const fileName = `wxfile://temp/WechatIMG${Date.now().toString().slice(-3)}.jpg`;
    const filePath = await java.fetch(who, daka_day);
    console.log('健康码', filePath)
    assert(fs.existsSync(filePath), '获取'+who+'健康码失败！');
    const fileKey = await uploadOss(filePath);
    return { file: fileName, id: fileKey };
}

// 行程码
async function genXCM(who) {
    console.log('行程码', daka_day)
    const fileName = `wxfile://temp/WechatIMG${Date.now().toString().slice(-3)}.jpg`;
    const filePath = await java.fetch(who, daka_day);
    console.log('行程码', filePath)
    assert(fs.existsSync(filePath), '获取'+who+'行程码失败！');
    const fileKey = await uploadOss(filePath);
    return { file: fileName, id: fileKey };
}

async function getOssParams() {
    const res = await POST('https://a.welife001.com/applet/getOssParams', {});
    return res.data;
}

async function uploadOss(src, name) {
    const radom = name || Date.now() + Date.now().toString().substr(5) + '.jpg'; // 每次生成新的文件名
    // const radom = name || (new Date(daka_day).getTime() + new Date(daka_day).getTime().toString().substring(0, 8) + '.jpg'); // 按日期固定文件名，覆盖上传
    const key = `${conf.openId}_image/${radom}`; // oss key
    console.log('uploadOss', key);
    const form = new FormData();
    form.append('key', key);
    const pms = await getOssParams();
    form.append('OSSAccessKeyId', pms.OSSAccessKeyId);
    form.append('policy', pms.policy);
    form.append('signature', pms.signature);
    form.append('file', fs.createReadStream(src));
    const res = await UPLOAD(`https://campus002.welife001.com/`, form);
    console.log('https://img.welife001.com/' + key);
    if (res !== '') {
        console.log('上传OSS文件失败！');
    }
    return key; // 上传文件失败了，也提交作业
}

async function getParent() {
    const res = await GET(`https://a.welife001.com/info/getParent?type=-1&members=${conf.memberId}&page=0&size=10&date=-1&hasMore=true`);
    return res.data;
}

function headers() {
    return {
        'Host': 'a.welife001.com',
        'Content-Type': 'application/json', // content-length不要传，传正确的反而报错
        'Accept-Language': 'zh-cn',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'Accept': '*/*',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E217 MicroMessenger/6.8.0(0x16080000) NetType/WIFI Language/en Branch/Br_trunk MiniProgramEnv/Mac',
        'Referer': 'https://servicewechat.com/wx23d8d7ea22039466/1069/page-frame.html',
        'imprint': conf.openId,
    }
}

async function GET(url) {
    return await REQUEST('GET', url, headers());
}

async function POST(url, body) {
    return await REQUEST('POST', url, headers(), JSON.stringify(body));
}

async function UPLOAD(url, form) {
    const headers = form.getHeaders();
    headers['Host'] = 'campus002.welife001.com';
    headers['User-Agent'] = 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E217 MicroMessenger/6.8.0(0x16080000) NetType/WIFI Language/en Branch/Br_trunk MiniProgramEnv/Mac';
    headers['Referer'] = 'https://servicewechat.com/wx23d8d7ea22039466/1069/page-frame.html';
    return await REQUEST('POST', url, headers, form);
}

async function REQUEST(method, url, headers, body) {
    console.log('==>', method, url);
    console.log('==>', typeof body === 'object' ? JSON.stringify(body) : body);
    return await fetch(url, {
        method: method,
        headers: headers,
        body: body,
    }).then(res => {
        console.log('<==', res.status, res.statusText);
        const resCT = res.headers.get('content-type') || '';
        return resCT.indexOf('json') !== -1 ? res.json() : res.text();
    }).then(data => {
        console.log('<==', JSON.stringify(data));
        return data;
    })
}

function today() {
    const d = new Date();
    return [d.getFullYear(), ('0' + (d.getMonth() + 1)).slice(-2), ('0' + d.getDate()).slice(-2)].join('-');
}

function wd() {
    const arr = [36.6, 36.7, 36.8, 36.9, 37];
    return arr[Math.floor((Math.random() * arr.length))];
}